package javango.contrib.jquery.widgets;

import java.util.Map;

import com.google.inject.Inject;

import javango.conf.Settings;
import javango.contrib.hibernate.ModelChoiceField;
import javango.contrib.jquery.JqueryWidget;
import javango.forms.fields.BoundField;
import javango.forms.widgets.SelectWidget;
import javango.forms.widgets.Util;

public class JQuerySelectWidget extends SelectWidget implements JqueryWidget {

	Settings settings;
	boolean smallList = true;
	
	@Override
	public String render(String name, Object value, Map<String, Object> attrs) {
		if (getField().getChoiceCount() <= 50) {
			return super.render(name, value, attrs);
		}
		smallList = false;
		
		Map<String, Object> finalAttrs = buildAttrs(attrs);
		finalAttrs.put("type", "text");
		finalAttrs.put("name", name);
		
		if (finalAttrs.containsKey("id")) {
			finalAttrs.put("id", String.format((String)finalAttrs.get("id"), name));
		}
		
		if (value != null) {
			if (value instanceof String) {
				if (!"".equals(value)) {
					finalAttrs.put("value", value);
				}				
			} else if (value instanceof String[]){
				String[] values = (String[])value;
				if (values.length > 0 && !"".equals(values[0])) {
					finalAttrs.put("value", values[0]);
				}	
			} else {
				finalAttrs.put("value", value.toString());
			}
		}
				
		return String.format("<input%s />", Util.flatatt(finalAttrs));
	}

	public String getScript(BoundField field) {		
		if (!field.getField().isEditable() || smallList) return "";
		
		// TODO Auto-generated method stub
		if (field.getField() instanceof ModelChoiceField) {
			ModelChoiceField modelChoiceField = (ModelChoiceField) field.getField();
			
			String jqueryUrl = settings.get("jquery_baseurl");
			return String.format("$(\"#id_%s\").autocomplete(\"%s/lookup/%s/\");", 
					(String)field.getHtmlName(),
					jqueryUrl,
					modelChoiceField.getModel().getCanonicalName());
		}
		return "<!-- " + field.getHtmlName() + " not a ModelChoiceField -->";
	}

	@Inject
	public JQuerySelectWidget(Settings settings) {
		super();
		this.settings = settings;
	}

}
